<template>
  <view class="picadd">
    <custom-head-top>
      <template #left>新增壁纸</template>
    </custom-head-top>
    <view class="main">
      <view class="grid">
        <view class="itemBox" v-for="(item, index) in picList" :key="index">
          <view class="close" @click="handleDelete(index)">X</view>
           <!-- 下方是语法糖写法 -->
          <editItem :item="item" v-model:item="picList[index]" />

        </view>
        <view class="itemBox add" @click="handleAdd" v-if="picList.length < 9">
          <view class="icon">+</view>
          <view class="text">点击选择图片</view>
        </view>
      </view>
      <view class="setClassify" v-if="picList.length">
        <uni-data-select
          ref="selectRef"
          collection="dc-bizhi-classify"
          field="_id as value, name as text ,sort"
          :where="`enable==true`"
          orderby="sort asc"
          clear
          placement="top"
          v-model="classify"
          @change="handleClassifyChange"
        ></uni-data-select>
      </view>

      <view class="btnGroup" v-if="picList.length">
        <button class="btn" type="primary" @click="handlePublish">发布</button>
        <button class="btn" type="warn" @click="handleClear">清空</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import customHeadTop from '@/components/cunstom-head-top/custom-head-top.vue';
import { ref } from 'vue';
import { showToast,showModal } from '@/utils/common';
import { compressImage } from '@/utils/tools';
import dayjs from 'dayjs';
import { cloudToHttp } from '../../utils/tools';
import { routerTo } from '@/utils/common';
import editItem from './children/editItem.vue';

const picCloudObj = uniCloud.importObject('admin-bizhi-picture')
const picList = ref([]);
const classify = ref(null);
const selectRef = ref(null);
const handleAdd = async () => {
  const res = await uni.chooseImage({
    count: 9,
  });
  const obj = {
    description: '',
    tempurl: '',
    score: '4.5',
    tabs: [],
    checked: true,
    picurl: '',
  };
  const list = res.tempFilePaths.map((item) => {
    return {
      ...obj,
      tempurl: item,
    };
  });
  picList.value = [...picList.value, ...list];
};
const handleDelete = async (index) => {
  const res = await showModal({
    content: '确定要删除吗？',
  });
  if (res === 'confirm') {
    picList.value.splice(index, 1);
  }
};
const handleClear = async () => {
  const res = await showModal({
    content: '确定要清空吗？',
  });
  if (res === 'confirm') {
    picList.value = [];
  }
};

const handleClassifyChange = (e) => {
  picList.value.forEach((item) => {
    item.classid = e;
  });
};
const handlePublish = async() => {
  if (!classify.value) {
    return showToast({
      title: '请选择分类',
    });
  }
uni.showLoading({
  title:'发布中...',
  mask:true
})
  const res = picList.value.every((item) => {
    return item.tempurl && item.description && item.score && item.tabs.length;
  });
  let errIndex = picList.value.findIndex((item) => {
    return !item.tempurl || !item.description || !item.score || !item.tabs.length;
  });
  if (!res) {
    return showToast({
      title: `第${errIndex + 1}张图片填写不完整`,
    });
  }

   const uploadRes = await Promise.all(picList.value.map(async (item,index) => {
    return uploadFile(item,index)

    })
  );

  picList.value = picList.value.map((item,index) => {
    const {tempurl,iptValue,...rest} = item
    return {
      ...rest,
      classid:classify.value,
      picurl: cloudToHttp(uploadRes[index].fileID)
    }
  })

 const result = await picCloudObj.add(picList.value)
 console.log("🌺 ~ result ~ result:🌳", result)
 if(result.errCode === 0){
  showToast({
    title:'发布成功'
  })
  setTimeout(() => {
    routerTo('/pages/bizhi/piclist','redirectTo')
  }, 1000);
 }else{
  showToast({
    title:result.errMsg,
  })
 }

  selectRef.value.clearVal();
};



const uploadFile = async (item,index) => {
const blob = await compressImage(item.tempurl)
return uniCloud.uploadFile({  // 这里return出去的是一个promise
  filePath: blob,
  cloudPath:`wallpaper/${dayjs().format('YYYYMMDD')}/${Date.now()}_${index}.webp`
})
  };
const handleUpdateItem = ($event,index) => {
  picList.value[index] = $event;
};
</script>
<style lang="less" scoped>
.main {
  padding: 20px;
  .grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: 20px;
    .itemBox {
      background-color: #f8f8f8;
      width: 100%;
      min-height: 300px;
      border: 1px solid transparent;
      display: flex;
      align-items: start;
      padding: 20px;
      box-sizing: border-box;
      position: relative;
      .close {
        position: absolute;
        top: 0;
        right: 0;
        width: 30px;
        height: 30px;
        background-color: red;
        color: #fff;
        display: none;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        font-size: 14px;
        font-weight: bold;
      }

      .left {
        width: 150px;
        aspect-ratio: 9/20;
        position: relative;
        background: conic-gradient(
          #ccc 0 25%,
          #fff 25% 50%,
          #ccc 50% 75%,
          #fff 75% 100%
        );
        background-size: 10px 10px;
        image {
          width: 100%;
          height: 100%;
        }
        .mask {
          background-color: rgba(0, 0, 0, 0.4);
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .icon {
            border-radius: 50%;
            flex: 1;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
          }
        }
      }
      .right {
        flex: 1;
        margin-left: 20px;
        color: #666;
        .row {
          margin-bottom: 20px;
          .label {
            font-size: 14px;
            margin-bottom: 6px;
          }
          .tabGroup {
            padding-top: 6px;
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            .tab {
              border: 1px solid #1a73e8;
              border-radius: 100px;
              color: #1a73e8;
              padding: 2px 6px;
              font-size: 12px;
              cursor: pointer;
            }
            .tab:hover {
              text-decoration: line-through;
            }
          }
        }
        .inline {
          display: flex;
          align-items: center;
          gap: 10px;
          .label {
            margin-bottom: 0;
          }
        }
      }
    }

    .itemBox.add {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #999;
      cursor: pointer;
      .icon {
        font-size: 50px;
      }
      .text {
        font-size: 20px;
        padding-top: 20px;
      }
    }
    .itemBox:hover {
      border-color: #e4e4e4;
      .close {
        display: flex;
      }
    }
  }
  .setClassify {
    padding: 30px 0;
    width: 430px;
  }
  .btnGroup {
    display: flex;
    margin: 0;
    gap: 30px;
    padding: 50px 0;
    button {
      width: 200px;
    }
  }
}
</style>
